<template>
  <el-container class="app-container">
    <el-collapse @change="handleCollapseChange"  v-model="collapseActiveName">
      <el-collapse-item :title="collapseTitle" name="1">
        <el-tabs type="border-card">
          <el-form :model="pageInfo" ref="form" label-width="80px" size="medium">
            <el-row>
              <el-col :span="8" :offset="0">
                <el-form-item prop="name" label="账号：">
                  <el-input v-model.trim='pageInfo.name' placeholder="请输入名称搜索"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="mobile" label="手机号：">
                  <el-input v-model.trim='pageInfo.mobile' placeholder="请输入手机号搜索"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="name" label="角色：">
                  <el-select v-model="pageInfo.roleId" clearable placeholder="请选择">
                    <el-option
                      v-for="(item,index) in addformrolelist"
                      :key="index"
                      :label="item.memo"
                      :value="item.roleId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class='tx-c'>
              <el-button type="primary" icon="el-icon-search" @click="submitForm('warehouseFilterForm')">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-row>
          </el-form>
        </el-tabs>
      </el-collapse-item>
    </el-collapse>
    <el-header class="m-t-20">
      <el-button @click="addAccountBtn" type="primary" icon="el-icon-plus">添加用户</el-button>
    </el-header>
    <!--表格-->
    <table-view
      :editBtnMap="true"
      :editBtnMapList="editBtnMapList"
      :columns="tableContent"
      :pageList="columnData"
      @edit-btnclick="editBtnClick"
      :templateDiv="{enable:true}"
    >
      <template slot="enable" slot-scope="scope">
        <el-tag :type="scope.row.enable?'success':'danger'" size="mini" effect="dark">{{ scope.row.enable?'正常':'停用' }}</el-tag>
      </template>
    </table-view>
    <!--分页-->
    <pagination-view  :pagesize="pageInfo.pageSize"
      :currentPage="pageInfo.pageNumber"
      :total="total"
      @size-change="sizeChange"
      @current-change="pageChange"
    ></pagination-view>

    <!--添加编辑，重置密码弹窗-->

    <el-dialog :title="showtitle" :visible.sync="dialog" width="40%" :show-close="true" :before-close="resetForms"
               :destroy-on-close="true" center>
      <!--添加form-->
      <el-form
        v-show="showType==='add' || showType === 'view'"
        :model="addform"
        :rules="addformrules"
        ref="addform"
        label-width="130px"
      >
        <el-form-item label="账号名称：" prop="username">
          <span v-if="showType!=='add'">{{addform.username}}</span>
          <el-input v-else v-model="addform.username" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realname">
          <span v-if="showType==='view'">{{addform.realname}}</span>
          <el-input v-else v-model="addform.realname" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <span v-if="showType==='view'">{{addform.mobile}}</span>
          <el-input v-else v-model="addform.mobile" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-radio-group v-model="addform.roleId">
            <el-radio
              v-for="(item, index) in addformrolelist"
              :key="index"
              :label="item.roleId">
              {{item.memo}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号备注：" prop="memo">
          <span v-if="showType==='view'">{{addform.memo}}</span>
          <el-input v-else type="textarea" v-model="addform.memo"></el-input>
        </el-form-item>

        <el-form-item v-if="showType==='add'" label="密码：" prop="password">
          <el-input v-model.trim="addform.password" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showType==='add'" label="确认密码：" prop="confirm_password">
          <el-input v-model.trim="addform.confirm_password" clearable></el-input>
        </el-form-item>
        <el-form-item label="账号状态：" prop="enabled" :disabled="showType==='view'">
          <el-radio-group v-model="radio">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <!--编辑form-->
      <el-form
        v-show="showType === 'edit'"
        :model="editform"
        :rules="editformrules"
        ref="editform"
        label-width="130px">
        <el-form-item label="账号名称：" prop="username">
          <span>{{editform.username}}</span>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realname">
          <el-input v-model.trim="editform.realname" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <el-input v-model.trim="editform.mobile" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roleIds">
          <el-radio-group v-model="editform.roleId">
            <el-radio
              v-for="(item, index) in addformrolelist"
              :key="index"
              :label="item.roleId">
              {{item.memo}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号备注：" prop="memo">
          <el-input type="textarea" v-model="editform.memo"></el-input>
        </el-form-item>
        <el-form-item label="账号状态：" prop="enabled">
          <el-radio-group v-model="radio">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <!--重置密码-->
      <el-form
        v-show="showType==='reset'"
        :model="resetform"
        :rules="resetformrules"
        ref="resetform"
        label-width="130px"
      >
        <el-form-item label="密码：" prop="password">
          <el-input v-model.trim="resetform.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirm_password">
          <el-input v-model.trim="resetform.confirm_password" clearable></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" v-if="showType!=='view'">
          <el-button type="primary" @click="handleClick('sure')">{{btnword}}</el-button>
          <el-button @click="handleClick('cancel')">取 消</el-button>
        </span>
    </el-dialog>
  </el-container>
</template>

<script>
    //import { mapGetters } from "vuex";
    //import TableFilter from "@/components/TableFilter";
    import TableView from '@/components/TableView'
    import PaginationView from '@/components/PaginationView'
    import userManage from '@/api/main/account/userManage'

    export default {
        name: 'roleManage',
        components: {
            PaginationView,
            TableView
        },
        data() {
            const validateConfirmPassWord = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('密码必填'))
                } else {
                    if (this.showType === 'add') {
                        if (this.addform.password != this.addform.confirm_password) {
                            return callback(new Error('密码不一致'))
                        } else {
                            callback()
                        }
                    } else {
                        if (this.resetform.password != this.resetform.confirm_password) {
                            return callback(new Error('密码不一致'))
                        } else {
                            callback()
                        }
                    }

                }
            }
            return {

                pageInfo: {
                    pageNum: 1,
                    pageSize: 20,
                    mobile: '',
                    name: '',
                    roleId: ''
                },
                tableContent: [{
                    field: 'username',
                    label: '账号名称'
                }, {
                    field: 'realname',
                    label: '真实姓名'
                }, {
                    field: 'mobile',
                    label: '联系电话'
                }, {
                    field: 'roleName',
                    label: '角色'
                }, {
                    field: 'createTime',
                    label: '创建时间'
                },{
                  field: 'enable',
                  label: '状态'
                }, {
                  field: 'memo',
                  label: '备注'
                }],
                // editBtnMapList: ['view', 'update', 'reset','switchStatus'],  //自定义的按钮内容
              editBtnMapList: ['update', 'delete'],  //自定义的按钮内容

              columnData: [],
                total:null,
                showType: 'add',     //添加账号 addform 编辑 editform 重置密码 resetpw
                addformrolelist: [],  //角色列表
                resetform: {
                    adminUserId: '',
                    password: '',
                    confirm_password: ''
                },
                resetformrules: {
                    password: [
                        {required: true, min: 6, trigger: 'blur'}
                    ],
                    confirm_password: [
                        {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
                    ]
                },
                addform: {
                    username: '',
                    realname: '',
                    roleId: '',
                    mobile: '',
                    password: '',
                    confirm_password: '',
                    enabled: 1,
                    memo: '',
                    adminUserId: ''
                },
                editform: {
                    username: '',
                    realname: '',
                    roleId: '',
                    mobile: '',
                    enabled: 1,
                    memo: '',
                    adminUserId: ''
                },
                editformrules: {
                    realname: [
                        {required: true, message: '请输入姓名'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符'}
                    ],
                    roleId: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                    mobile: [
                        {required: true, message: '请输入11位手机号', min: 11, max: 11}
                    ],
                    password: [
                        {required: true, min: 6, trigger: 'blur'}
                    ],
                    confirm_password: [
                        {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
                    ],
                    enabled: [
                        {required: true, message: '请选择状态', trigger: 'change'}
                    ]
                },
                addformrules: {
                    username: [
                        {required: true, min: 3, trigger: 'blur'}
                    ],
                    realname: [
                        {required: true, message: '请输入姓名'},
                        {min: 1, max: 20, message: '长度在 1 到 20 个字符'}
                    ],
                    roleId: [
                        {required: true, message: '请选择角色', trigger: 'change'}
                    ],
                    mobile: [
                        {required: true, message: '请输入11位手机号', min: 11, max: 11}
                    ],
                    password: [
                        {required: true, min: 6, trigger: 'blur'}
                    ],
                    confirm_password: [
                        {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
                    ],
                    enabled: [
                        {required: true, message: '请选择状态', trigger: 'change'}
                    ]
                },
                showtitle: '添加账号',
                btnword: '确定',
                dialog: false
            }
        },
        methods: {
            submitForm(formName) {
                this.getData()
            },
            resetForm(formName) {
                this.pageInfo = {
                    pageNum: 1,
                    pageSize: 20,
                    mobile: '',
                    name: '',
                    roleId: ''
                }
                this.dialog = false
                this.getData()
            },
            addAccountBtn() {
                this.setTitleType('添加账号', 'add', '确定')
            },

            editBtnClick(val, index, type) {
                let _this = this
                switch (type) {
                    case 'update':
                        _this.setTitleType('编辑账号', 'edit', '确定')
                        _this.getUserInfo(val.adminUserId)
                        break
                    case 'view':
                        _this.setTitleType('查看账号', 'view', '')
                        _this.getUserInfo(val.adminUserId)
                        break
                    case 'reset':
                        _this.setTitleType('重置密码', 'reset', '确定')
                        _this.getUserInfo(val.adminUserId)
                        break
                    case 'delete':
                        _this.delUser(val.adminUserId)
                        break
                  case 'switchStatus':
                    _this.changeUserStatus(val.adminUserId, val.enabled ? 0 : 1)
                    break
                }
            },
            handleData() {
                this.addform.enabled = Number(this.addform.enabled)
            },
            handleClick(type) {
                let _this = this
                let _refstype = _this.showType //添加账号 addform 编辑 editform 重置密码 resetpw
                switch (type) {
                    case 'sure':
                        _this.$refs[_refstype + 'form'].validate((valid) => {
                            if (valid) {
                                _this.handleData()
                                switch (_refstype) {
                                    case 'add':
                                        userManage.createUser(_this.addform, 'add').then(res => {
                                            _this.getData()
                                        })
                                        break
                                    case 'edit':
                                        userManage.createUser(_this.editform, 'edit').then(res => {
                                            _this.getData()
                                        })
                                        break
                                    case 'reset':
                                        userManage.createUser(_this.resetform, 'reset').then(res => {
                                            _this.resetForms()
                                        })
                                        break
                                    default:
                                        return null
                                }

                            } else {
                                return false
                            }
                        })
                        break
                    case 'cancel':
                        _this.resetForms()
                        break
                    default:
                        break
                }
            },
            setTitleType(title = '', type = 'addform', btnwold = '确定') {
                let _this = this
                _this.dialog = true
                _this.showtitle = title
                _this.showType = type
                _this.btnword = btnwold
            },
            resetForms() {
                let _this = this

                let type = _this.showType
                switch (type) {
                    case 'add':
                        _this.addform = {
                            username: '',
                            realname: '',
                            roleId: '',
                            mobile: '',
                            password: '',
                            confirm_password: '',
                            enabled: 1,
                            memo: ''
                        }
                        if (_this.$refs.addform) {
                            _this.$refs.addform.resetFields()
                        }
                        break
                    case 'edit':
                        _this.editform = {
                            username: '',
                            realname: '',
                            roleId: '',
                            mobile: '',
                            enabled: 1,
                            memo: '',
                            adminUserId: ''
                        }
                        _this.$refs.editform.resetFields()
                        break
                    case 'reset':
                        _this.resetform = {
                            adminUserId: '',
                            password: '',
                            confirm_password: ''
                        }
                        _this.$refs.resetform.resetFields()
                        break
                }
                _this.dialog = false

            },
            //更改用户状态
            changeUserStatus(id, enabled) {
                userManage.changeUserStatus(id, enabled).then((res) => {
                  this.handleMessage(res)
                    if (res.code === '200') this.getData()
                })
            },
            //删除用户
            delUser(id) {
                let _this = this
                userManage.deleteUser(id).then((res) => {
                    if (res.code === '200') {
                        _this.$message.success(res.message)
                    }
                })
            },
            //拉取列表
            getData() {
                userManage.getUserList(this.pageInfo).then(res => {

                    this.columnData = res.body.records
                    this.total = Number(res.body.total)
                    this.pageInfo.pageNumber = Number(res.body.pageNumber) || 1
                    this.resetForms()
                })
            },
            getUserInfo(id) {
                let _this = this
                let type = _this.showType
                userManage.getUserInfo({adminUserId: id}).then(res => {
                    if (res.code === '200') {
                        switch (type) {
                            case 'view':
                                _this.addform = res.body
                                break
                            case 'edit':
                                _this.editform = res.body
                              break
                            case 'reset':
                                _this.resetform.adminUserId = res.body.adminUserId
                                break
                        }
                    }
                })
            },
            getRoleAll() {
                userManage.getRoleAll().then(res => {
                    if (res.code === '200') {
                        this.addformrolelist = res.body
                    }
                })
            },
            // pageSize变化函数
            sizeChange(val) {
                this.pageInfo.pageSize = val
                this.getData()
            },
            // page变化函数
            pageChange(val) {
                this.pageInfo.pageNumber = val
                this.getData()
            }
        },
        computed: {
            // ...mapGetters(["tableContent"])
        }
        ,
        created: function () {
            this.getData()
            // this.getRoleAll()
        }
    }
</script>
<style lang="scss">

</style>

